//
//  LZRestaurantViewController.m
//  laziz_Consumer
//
//  Created by XMac on 16/10/24.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZRestaurantViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UIButton+TransitionEdgeInsets.h"
#import "UITableView+LZTableView.h"
#import "BlocksKit+UIKit.h"
#import "LZRestaurantTableViewCell.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZRegionSelectView.h"
#import "LZSearchCollectionView.h"
#import "extobjc.h"
#import "Masonry.h"
#import "IQKeyboardManager.h"
#import "LAMerchantDetailViewController.h"
#import "LZSearchRestaurantListViewController.h"
#import "LZRestaurantPresenter.h"
#import "LZRestaurantListModel.h"
#import "LZRestaurantFiltersView.h"
#import "LZHomePageViewController.h"
#import "AppDelegate.h"
#import "CityManager.h"
#import "CitysModel.h"
#import "LZSearchPresenter.h"
#import "LZMapLocationManager.h"
#import "MJRefresh.h"
#import "LZSearchResultView.h"
#import "LZAlertView.h"
#import "LZSearchCityViewController.h"
#import "LZNoDataPublicView.h"

NSString *const kCellID = @"LZRestaurantTableViewCell";

@interface LZRestaurantViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, LZFilterViewDelegate>


@property(nonatomic, strong) NSArray *leftItems;

@property(nonatomic, strong) NSArray *rightItems;


@property(strong, nonatomic) IBOutlet UITableView *restaurantTableView;

@property(nonatomic, strong) UIView *visualView;

@property(nonatomic, strong) UISearchBar *searchBar;

@property(nonatomic, strong) NSMutableArray *arrData;

@property(nonatomic, strong) LZRestaurantFiltersView *filterView;

@property(nonatomic, strong) NSDictionary *filterKeywordsDic;

@property(nonatomic, strong) LZSearchCollectionView *searchCollectionView;

@property(nonatomic , strong) LZSearchResultView *searchResultView;

@property(nonatomic, strong) LZRegionSelectView *regionSelectView;

@property(nonatomic, strong) UIImageView *logoImgView;

@property(nonatomic, assign) BOOL showSearchCity;

@property (nonatomic, strong) LZSearchCityViewController *searchCityVC;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;
@property (nonatomic, assign) NSTimeInterval timestamp;
/*标记: 筛选时筛选了距离参数, 但当前数据列表的城市和定位城市不一致, 用户点击 同意 切换数据列表城市为当前城市,默认NO*/
@property (nonatomic, assign) BOOL  isChangeCurrentDataCityWhenFilterDicHaveDistance;

@end


@implementation LZRestaurantViewController {
    LZSearchCollectionView *_searchCollectionView;
}

#pragma
#pragma mark vc life cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.umLogPageViewName = @"商户列表页面";
    
    [self configNavigationBar];

    [self configUI];

    [self configureFilterView];

    [self configureRestaurantSearchView];

    [self registCell];

    [self configureRefresh];

    [self initDataResource];

    [self.restaurantTableView.mj_header beginRefreshing];
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    
    self.isNotShowNavBarShadow = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma
#pragma mark - private method

- (void)initDataResource {
    self.arrData = [NSMutableArray array];
    self.page = 1;
    self.limit = 10;
    self.timestamp = 0;
    self.isChangeCurrentDataCityWhenFilterDicHaveDistance = NO;
}

- (void)configUI {
    
    self.restaurantTableView.backgroundColor = UIColorFromRGB(0xeeeeee, 1);

    self.restaurantTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    
    [[CityManager shareManager] addObserver:self forKeyPath:@"currentShowCityModel" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    
    [self.regionSelectView changeTitle:[CityManager shareManager].currentShowCityModel.name];
    
    self.searchCityVC.selectCityModel = [CityManager shareManager].currentShowCityModel;
    
    self.navigationItem.titleView = self.logoImgView;
}

- (void)registCell {
    self.restaurantTableView.separatorColor = [UIColor clearColor];
    [self.restaurantTableView registerNib:[UINib nibWithNibName:kCellID bundle:nil] forCellReuseIdentifier:kCellID];
}

- (void)configureRefresh
{
    self.restaurantTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downLoadNewRestaurantListData)];
    [self.restaurantTableView configHeaderRefreshText];
    
    
    self.restaurantTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreRestaurantListData)];
    [self.restaurantTableView configFooterRefreshText];
}

- (void)leftBarButtonAction {
    self.searchCityVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:self.searchCityVC animated:YES];
}


/**
 显示热搜界面或者显示城市选择界面，根据所传的参数来确定。

 */
- (void)showSearchView
{
    self.searchCollectionView.hidden = NO;
    
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationItem.rightBarButtonItems = nil;
    self.navigationItem.titleView = self.searchBar;

    [self.visualView updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(SCREEN_HEIGHT-64);
    }];

    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        [self.view layoutIfNeeded];

    }                completion:^(BOOL finished) {
        [self.searchBar becomeFirstResponder];
        [self.searchCollectionView refreshUserdefaultData];
        [self requestHotSearch];
    }];
}


/**
 隐藏热搜界面
 */
- (void)hiddenSearchView {
    self.navigationItem.titleView = self.logoImgView;
    [self navigationItemSetting:_leftItems type:NAVIGATIONITEMSETTING_LEFT];
    [self navigationItemSetting:_rightItems type:NAVIGATIONITEMSETTING_RIGHT];

    [self.visualView updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];


    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        [self.view layoutIfNeeded];

    }                completion:^(BOOL finished) {
        self.searchBar.text = @"";
    }];
    
}


/**
 显示搜索结果界面

 @param searchContent 搜索内容
 */
-(void)showSearchResultView:(NSString *)searchContent{
    self.searchCollectionView.hidden = YES;
    //如果是一次性的cancel需要热搜和搜索结果一起消失，所以不能设置搜索界面为可现实 ，
    if (self.searchResultView && searchContent.length != 0) {
        self.searchResultView.hidden = NO;
    }
    
    if (searchContent.length == 0) {
        [self hideSearchResultView];
    } else {
        if (!_searchResultView) {
            _searchResultView = [LZSearchResultView new];
            @weakify(self)
            [_searchResultView setSelectBlock:^(NSString *idStr,NSString *type,NSString *objId) {
                //todo 跳转餐厅列表
                DLog(@"id str %@",idStr);
                @strongify(self)
                [self pushSearchRestaurantViewControllerWithSearchMessage:idStr andType:type andObjId:objId];
            }];
        }
        
        
        BOOL isAdded = NO;
        for (UIView *view in self.visualView.subviews) {
            isAdded = [view isEqual:_searchResultView];
        }
        
        if (!isAdded) {
            [self.visualView addSubview:_searchResultView];
            
            [_searchResultView makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
        }
        
        [self requestKeywordsSearch:searchContent];
    }
}


/**
 隐藏搜索结果界面
 */
-(void)hideSearchResultView{
    
    self.searchCollectionView.hidden = NO;
    
    [_searchResultView removeFromSuperview];
    _searchResultView = nil;
    
    self.searchBar.text = @"";
}


- (void)configNavigationBar {

    ///背景模糊
//    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];

    _visualView = [[UIView alloc] init];
    _visualView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_visualView];

    [_visualView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.top).offset(0);
        make.leading.mas_equalTo(0);
        make.width.equalTo(CGRectGetWidth(self.view.frame));
        make.height.mas_equalTo(0);
    }];

    _searchBar = [UISearchBar new];
    _searchBar.showsCancelButton = YES;
    _searchBar.placeholder = LZLocalizedString(@"search_placeholder_search", nil);
    _searchBar.delegate = self;
    _searchBar.tintColor = UIColorFromRGB(0xff6600, 1);

    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 14.0f;
        searchField.layer.borderColor = UIColorFromRGB(0xcccccc, 1).CGColor;
        searchField.layer.borderWidth = 1;
        searchField.layer.masksToBounds = YES;
    }


    UIButton *searchButton = ({
        UIImage *btn_image = [UIImage imageNamed:@"search_icon"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 40, 40);
        [button setImage:btn_image forState:UIControlStateNormal];
        [button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(button.bounds)-btn_image.size.width, 0, 0)];

        @weakify(self)
        [button bk_addEventHandler:^(UIButton *sender) {
            @strongify(self)

            [self showSearchView];

        }         forControlEvents:UIControlEventTouchUpInside];
        button;
    });

    UIButton *filterButton = ({
        UIImage *btn_image = [UIImage imageNamed:@"filtrate_icon"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, btn_image.size.width+9, 40);
        [button setImage:btn_image forState:UIControlStateNormal];
        [button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(button.bounds)-btn_image.size.width, 0, 0)];

        @weakify(self)
        [button bk_addEventHandler:^(id sender) {
            @strongify(self)
            [self.filterView showSelfAnimation];
        }         forControlEvents:UIControlEventTouchUpInside];
        button;
    });

    _leftItems = @[self.regionSelectView];

    _rightItems = @[filterButton, searchButton];

    [self navigationItemSetting:_leftItems type:NAVIGATIONITEMSETTING_LEFT];

    [self navigationItemSetting:_rightItems type:NAVIGATIONITEMSETTING_RIGHT];
}

- (void)configureFilterView {
    NSArray *cuisineArrTemp;
    NSArray *hotAreaArrTemp;
    AppDelegate *del = (AppDelegate *) [UIApplication sharedApplication].delegate;
    UITabBarController *rootVc = (UITabBarController *) del.window.rootViewController;
    UINavigationController *navVc = rootVc.viewControllers[0];
    for (id vc in navVc.viewControllers) {
        if ([vc isKindOfClass:[LZHomePageViewController class]]) {
            LZHomePageViewController *homeVc = (LZHomePageViewController *) vc;
            cuisineArrTemp = homeVc.cuisineArr;
            hotAreaArrTemp = homeVc.hotAreaArr;
        }
    }

    UIWindow *w = [UIApplication sharedApplication].keyWindow;

    self.filterView = [[LZRestaurantFiltersView alloc] init];
    self.filterView.isForRestaurant = YES;
    self.filterView.cuisineDataArr = [NSMutableArray arrayWithArray:cuisineArrTemp];
    self.filterView.hotAreasDataArr = [NSMutableArray arrayWithArray:hotAreaArrTemp];;
    self.filterView.filterViewDelegate = self;
    [w addSubview:self.filterView];
    [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];

}

//配置城市筛选结果视图
- (void)configureRestaurantSearchView {
    [_visualView addSubview:self.searchCollectionView];

    [self.searchCollectionView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.and.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(-49).priority(750);
    }];
}

#pragma
#pragma mark - request

- (void)downLoadNewRestaurantListData {
    [self requestRestaurantListDataWithPage:1 andLimit:self.limit isDownLoad:YES];
}

- (void)upLoadMoreRestaurantListData {
    [self requestRestaurantListDataWithPage:self.page andLimit:self.limit isDownLoad:NO];
}

- (void)requestRestaurantListDataWithPage:(int)page andLimit:(int)limit isDownLoad:(BOOL)isDownLoad {
    
    NSMutableDictionary *dic;
    
    if (self.filterKeywordsDic) {
        dic = [self.filterKeywordsDic mutableCopy];
    }
    else {
        dic = [NSMutableDictionary dictionary];
    }
    
    if ([LZMapLocationManager shareLocationManager].currentLocation) {
        dic[@"mapLocationLongitude"] = [NSNumber numberWithDouble:[LZMapLocationManager shareLocationManager].currentLocation.coordinate.longitude];
        dic[@"mapLocationLatitude"] = [NSNumber numberWithDouble:[LZMapLocationManager shareLocationManager].currentLocation.coordinate.latitude];
    }
    
    if ([CityManager shareManager].currentShowCityModel) {
        dic[@"cityCode"] = [CityManager shareManager].currentShowCityModel.cityNO;
    }
    
    if (!isDownLoad && self.timestamp>0) {
        dic[@"timestamp"] = [NSNumber numberWithDouble:self.timestamp];
    }
    
    WS(weakSelf)
    [LZRestaurantPresenter getRestaurantListWithFilterPrameter:dic PageNum:page pageLimit:self.limit ResultSuccess:^(NSMutableArray *listArr,int nowPage,NSTimeInterval timestamp) {
        
        BOOL isShouldAddArray = NO;
        
        if (isDownLoad) {
            [weakSelf.restaurantTableView.mj_header endRefreshing];
            weakSelf.timestamp = timestamp;
            weakSelf.page = 1+1;
            [weakSelf.arrData removeAllObjects];
            isShouldAddArray = YES;
            if (weakSelf.restaurantTableView.mj_footer.state == MJRefreshStateNoMoreData) {
                weakSelf.restaurantTableView.mj_footer.state = MJRefreshStateIdle;
            }
        }
        else {
            [weakSelf.restaurantTableView.mj_footer endRefreshing];
            if (nowPage == weakSelf.page) {
                // 如果返回的页数是请求的页数
                weakSelf.page ++;
                isShouldAddArray = YES;
            }
        }
        
        if (isShouldAddArray) {
            [weakSelf.arrData addObjectsFromArray:listArr?:@[]];
            [weakSelf.restaurantTableView reloadData];
            if (listArr.count == 0) {
                if (weakSelf.arrData.count == 0) {
                    [weakSelf.restaurantTableView setNullStringFooterText];
                }
                else {
                    [weakSelf.restaurantTableView setNoMoreDataFooterText];
                }
                weakSelf.restaurantTableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
            
            if (weakSelf.arrData.count == 0) {
                [LZNoDataPublicView showNoDataViewInView:weakSelf.restaurantTableView];
            }
            else {
                [LZNoDataPublicView hiddenNoDataViewInView:weakSelf.restaurantTableView];
            }
            
        }
        
    } ResultFailed:^(NSString *remind) {
        if (isDownLoad) {
            [weakSelf.restaurantTableView.mj_header endRefreshing];
        }
        else {
            [weakSelf.restaurantTableView.mj_footer endRefreshing];
        }
    }];
    
    
}


/**
 热搜请求
 */
- (void)requestHotSearch {
    LZSearchPresenter *searchPresenter = [LZSearchPresenter new];
    [searchPresenter hotSearch:@"0" onSuccess:^(id data) {
        //todo 请求后发送给 searchCollectionView 去显示数据
        [self.searchCollectionView refreshData:data[@"data"]];

    } onFail:^(NSString *fail) {
        DLog(@"fail %@",fail);
    }];
}



/**
 关键字搜索

 @param searchContent 搜索关键字
 */
-(void)requestKeywordsSearch:(NSString *)searchContent{
    LZSearchPresenter *searchPresenter = [LZSearchPresenter new];
    @weakify(self);
    [searchPresenter keywordsSearch:searchContent type:0 onSuccess:^(id data) {
        @strongify(self);
        [self.searchResultView refreshDatas:data];
    } onFail:^(NSString *fail) {
        DLog(@"fail %@",fail);
    }];
}

#pragma mark -
#pragma mark event

- (void)pushSearchRestaurantViewControllerWithSearchMessage:(NSString*)searchMsg andType:(NSString*)type andObjId:(NSString*)objId{
    LZSearchRestaurantListViewController *vc = [[LZSearchRestaurantListViewController alloc] init];
    vc.searchMessage = [searchMsg copy];
    vc.searchType = [type copy];
    vc.searchId = [objId copy];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -
#pragma mark search city KVO 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentShowCityModel"]) {
        
        [self.regionSelectView changeTitle:[CityManager shareManager].currentShowCityModel.name];

        self.searchCityVC.selectCityModel = [CityManager shareManager].currentShowCityModel;
        
        [self hiddenSearchView];

        if (self.isChangeCurrentDataCityWhenFilterDicHaveDistance == NO) {
            if (_filterKeywordsDic.count > 0) {
                _filterKeywordsDic = nil;
            }
            
            [self.filterView clearFilterResult];
        }
        
        [self.restaurantTableView.mj_header beginRefreshing];

        if (self.isViewLoaded && self.isChangeCurrentDataCityWhenFilterDicHaveDistance == NO && self.view.window) {
            DLog(@"是当前显示vc")
            // 如果定位的城市不在app服务的城市内
            if ([[CityManager shareManager].currentShowCityModel.cityNO isEqualToString:@"00001"]) {
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_location_not_server_city_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
                
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    if (index == 1) {
                        // 去选择城市
                        [self leftBarButtonAction];
                    }
                };
            }
        }
        
        if (self.isChangeCurrentDataCityWhenFilterDicHaveDistance == YES) {
            self.isChangeCurrentDataCityWhenFilterDicHaveDistance = NO;
        }
    }
}

#pragma mark -
#pragma mark filterview delgate

- (void)returnTheFileterResult:(NSDictionary *)dic {
 
    //如果筛选项中包含了距离参数. 并且当前定位的城市和城市列表选择的城市不一致.提醒用户是否要切换城市
    if ([dic.allKeys containsObject:@"distance"] && ![[CityManager shareManager].locationCityModel.cityNO isEqualToString:[CityManager shareManager].currentShowCityModel.cityNO]) {
        
        LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"filter_distance_not_same_city", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
        [alert show];
        @weakify(self);
        alert.clickButtonIndexBlock = ^(NSInteger index) {
            @strongify(self);
            if (index == 1) {//数据列表切换到当前定位城市
                //数据切换到当前
                self.isChangeCurrentDataCityWhenFilterDicHaveDistance = YES;
                self.filterKeywordsDic = dic;
                [CityManager shareManager].currentShowCityModel = [CityManager shareManager].locationCityModel;
                [self.restaurantTableView.mj_header beginRefreshing];
            }else{
                self.filterKeywordsDic = dic;
                [self.restaurantTableView.mj_header beginRefreshing];
                
            }
        };
    }else{//如果没有包含,则直接筛选
        _filterKeywordsDic = dic;
        [self.restaurantTableView.mj_header beginRefreshing];
    }

}

#pragma
#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arrData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier:kCellID cacheByIndexPath:indexPath configuration:^(id cell) {

    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    LZRestaurantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    cell.type = CellType_Normal;
    cell.isShowDistance = [LZMapLocationManager shareLocationManager].currentLocation?YES:NO;
    if (self.arrData.count > indexPath.row) {
        cell.model = self.arrData[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LZRestaurantListModel *model = self.arrData[indexPath.row];
    
    LAMerchantDetailViewController *vc = [[LAMerchantDetailViewController alloc] init];
    vc.restaurantId = [model.restaurantId copy];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma
#pragma mark UISearchBarDelegate

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self hideSearchResultView];
    [self hiddenSearchView];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    //todo 显示搜索结果界面，隐藏热搜界面
    [self showSearchResultView:searchText];
}

/* **********  以下是用于解决 UISearchBar失去第一响应者身份后,取消按钮不执行点击事件 的问题 ********** */
    
// UISearchBar结束编辑
    
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    [self searchBarResignAndChangeUI];
    
}

// searchBarResignAndChangeUI方法的实现如下：
    
- (void)searchBarResignAndChangeUI{
    
    [_searchBar resignFirstResponder];//失去第一响应
    
    [self changeSearchBarCancelBtnTitleColor:_searchBar];//改变布局
    
}

- (void)changeSearchBarCancelBtnTitleColor:(UIView *)view{
    
    if (view) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *getBtn = (UIButton *)view;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [getBtn setEnabled:YES];//设置可用
                
                [getBtn setUserInteractionEnabled:YES];
            });
            
            [getBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateReserved];
            
            [getBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateDisabled];
            
            return;
            
        }else{
            
            for (UIView *subView in view.subviews) {
                [self changeSearchBarCancelBtnTitleColor:subView];
            }
            
        }
    }else{
        return;
    }
}

/* ************************************************************************ */

#pragma mark -
#pragma mark 初始化

- (LZSearchCollectionView *)searchCollectionView {
    if (!_searchCollectionView) {
        _searchCollectionView = [[LZSearchCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[UICollectionViewFlowLayout new]];
        
        @weakify(self)
        [_searchCollectionView setMostSearchSelectBlock:^(NSString *searchContent) {
            @strongify(self)
            self.searchBar.text = searchContent;
            [self showSearchResultView:searchContent];
        }];
        
        [_searchCollectionView setHistorySelectBlock:^(NSString *name,NSString *type,NSString *objId) {
            //todo 跳转餐厅列表
            DLog(@"id str %@",name);
            @strongify(self)
            [self pushSearchRestaurantViewControllerWithSearchMessage:name andType:type andObjId:objId];
        }];
    }

    return _searchCollectionView;
}


- (LZRegionSelectView *)regionSelectView {
    if (!_regionSelectView) {
        _regionSelectView = [[LZRegionSelectView alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
        _regionSelectView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBarButtonAction)];
        [_regionSelectView addGestureRecognizer:tap];
    }
    return _regionSelectView;
}

- (UIImageView *)logoImgView
{
    if (!_logoImgView) {
        _logoImgView = [[UIImageView alloc] init];
        _logoImgView.frame = CGRectMake(0, 0, 61, 15.5);
        _logoImgView.image = [UIImage imageNamed:@"logo_new"];
    }
    
    return _logoImgView;
}

- (LZSearchCityViewController *)searchCityVC
{
    if (!_searchCityVC) {
        _searchCityVC = [[LZSearchCityViewController alloc] init];
    }
    
    return _searchCityVC;
}

@end
